package org.study.meilisearch.boot.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 采用 Meilisearch 实现的商品搜索功能
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年04月27日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@RestController
@RequestMapping("/product")
public class ProductController {
    private static final String INDEX_NAME = "product";
    private final Client client;

    /**
     * 创建索引并导入商品数据
     */
    @GetMapping("/createIndex")
    public TaskInfo createIndex() throws IOException {
        ClassPathResource resource = new ClassPathResource("json/products.json");
        String jsonStr = IoUtil.read(resource.getInputStream(), StandardCharsets.UTF_8);
        TaskInfo info = client.index(INDEX_NAME).addDocuments(jsonStr, "id");
        return info;
    }

    /**
     * 修改索引设置
     */
    @GetMapping("/updateSettings")
    public TaskInfo updateSettings() {
        Settings settings = new Settings();
        settings.setFilterableAttributes(new String[]{"productCategoryName"});
        settings.setSortableAttributes(new String[]{"price"});
        TaskInfo info = client.index(INDEX_NAME).updateSettings(settings);
        return info;
    }

    /**
     * 根据关键字分页搜索商品
     */
    @GetMapping(value = "/search")
    public Searchable search(@RequestParam(required = false) String keyword,
                             @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                             @RequestParam(required = false) String productCategoryName,
                             @RequestParam(required = false, value = "0->按价格升序；1->按价格降序") Integer order) {
        SearchRequest.SearchRequestBuilder searchBuilder = SearchRequest.builder();
        searchBuilder.page(pageNum);
        searchBuilder.hitsPerPage(pageSize);
        if (StrUtil.isNotEmpty(keyword)) {
            searchBuilder.q(keyword);
        }
        if (StrUtil.isNotEmpty(productCategoryName)) {
            searchBuilder.filter(new String[]{"productCategoryName=" + productCategoryName});
        }
        if (order != null) {
            if (order == 0) {
                searchBuilder.sort(new String[]{"price:asc"});
            } else if (order == 1) {
                searchBuilder.sort(new String[]{"price:desc"});
            }
        }
        Searchable searchable = client.index(INDEX_NAME).search(searchBuilder.build());
        return searchable;
    }
}
